package com.train.mgr.modules.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.train.common.enums.CheckStatusEnum;
import com.train.common.enums.UserTypeEnum;
import com.train.common.exception.BizException;
import com.train.common.exception.BusinessException;
import com.train.common.model.PageParam;
import com.train.common.model.PageResult;
import com.train.common.utils.AuthUtils;
import com.train.common.utils.StringUtils;
import com.train.common.utils.ToolUtil;
import com.train.mgr.modules.biz.dto.request.*;
import com.train.mgr.modules.biz.dto.response.EmployeeRespDTO;
import com.train.mgr.modules.biz.entity.CourseUser;
import com.train.mgr.modules.biz.entity.Customer;
import com.train.mgr.modules.biz.mapper.CourseUserMapper;
import com.train.mgr.modules.biz.mapper.CustomerMapper;
import com.train.mgr.modules.system.dto.request.UserPageReqDTO;
import com.train.mgr.modules.system.dto.request.UserPassReqDTO;
import com.train.mgr.modules.system.dto.request.UserReqDTO;
import com.train.mgr.modules.system.dto.response.UserRespDTO;
import com.train.mgr.modules.system.entity.User;
import com.train.mgr.modules.system.mapper.UserMapper;
import com.train.mgr.modules.system.service.AuthService;
import com.train.mgr.modules.system.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author cxg
 * @desc 用户管理 service
 * @date 2023/02/01 16:35
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final PasswordEncoder passwordEncoder;
   // private final UserRoleService userRoleService;
    private final AuthService authService;

    @Autowired
    private final CustomerMapper customerMapper;

    @Autowired
    private CourseUserMapper courseUserMapper;


    private static final String PSSWORD_REGEX = "^[a-zA-Z0-9`~!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>\\/?]{6,20}$";
    /** 正则：汉字、字母、数字、英文句号 */
    private static final Pattern PATTERN_USERNAME = Pattern.compile("^[\\u4e00-\\u9fa5A-Za-z0-9.]{1,20}$");
    /** 错误提示语 */
    private static final String ERROR_MSG = "只能输入汉字、字母、数字、()";
    private static final Pattern pattern = Pattern.compile(PSSWORD_REGEX);

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer add(UserReqDTO body) {
        this.checkParams(body);
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        User entity = BeanUtil.copyProperties(body, User.class, "id");
        entity.setPassword(passwordEncoder.encode(body.getPass()));
        entity.setOriginalPwd(body.getPass());
        entity.setPhone(body.getUsername());
        entity.setUserLable(body.getUserLable());
        entity.setCustomerId(customerId);
        entity.setCreateBy(AuthUtils.getCurrentUser().getNickName());

        //如果是添加企业员工
        if(body.getUserType().equals(UserTypeEnum.EMPLOYEE.getCode())){
            Customer custBean =  customerMapper.selectById(customerId);
            if(ObjectUtil.isEmpty(custBean) || custBean.getIsDeleted().equals(1)){
                throw new BizException("企业信息为空");
            }
            entity.setEmpCheckState(custBean.getCheckMode());//企业员工审核状态（0-未审核，1-审核通过）
        }
        Integer result = baseMapper.insert(entity);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer delete(List<Long> ids) {
        // 不能删除自己
        Long userId = AuthUtils.getUserId();
        if (CollUtil.contains(ids, userId)) {
            throw new BizException("不能删除自己登录的账号");
        }
        // 删除用户角色
       // userRoleService.deleteByUserIds(ids);
        // 删除用户
        int result = baseMapper.deleteBatchIds(ids);
        // 清除 session
        authService.removeUserSession(ids);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer update(UserReqDTO body) {
        checkParams(body);
        User tmpUser = getById(body.getId());
        if(ObjectUtils.isNull(tmpUser)){
            throw new BusinessException("您好，用户不存在～");
        }
        User user = BeanUtil.copyProperties(body, User.class);
        user.setOriginalPwd(body.getPass());
        user.setPassword(passwordEncoder.encode(body.getPass()));
        user.setPhone(body.getUsername());//账号就是手机号

        int result = baseMapper.updateById(user);
        if (body.getEnabled() == 1) {
            authService.removeUserSession(body.getId());
        }
        return result;
    }

    @Override
    public UserRespDTO get(Long id) {
        User user = getById(id);
       // List<UserRole> userRoles = userRoleService.findByUserId(id);
        //List<Long> roles = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        UserRespDTO userRespDTO = BeanUtil.copyProperties(user, UserRespDTO.class);
       // userRespDTO.setRoles(roles);
        return userRespDTO;
    }



    @Override
    public PageResult<UserRespDTO> page(UserPageReqDTO params) {
        Page<User> page = params.buildPage();
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.and(
                StrUtil.isNotBlank(params.getQ()),
                wrapper -> wrapper.like(User::getUsername, params.getQ())
                        .or()
                        .like(User::getNickName, params.getQ())
        );
        //如果当前登录用户是运营管理用户
        if(UserTypeEnum.MGR_USER.getCode().toString().equals(AuthUtils.getCurrentUser().getUserType())){
            queryWrapper.eq( User::getUserType, UserTypeEnum.MGR_USER.getCode());
        }

        //如果当前登录用户是企业管理用户，则查询对应企业用户列表
        if(UserTypeEnum.ETP_USER.getCode().toString().equals(AuthUtils.getCurrentUser().getUserType())){
            queryWrapper.eq(AuthUtils.getCurrentUser().getCustomerId()!=null, User::getCustomerId, AuthUtils.getCurrentUser().getCustomerId());
            queryWrapper.eq(User::getUserType, UserTypeEnum.ETP_USER.getCode());
            queryWrapper.eq(User::getIsInitEtp,"0");//是否初始化第一个企业管理者（1-是）
        }

        queryWrapper.ne(User::getUsername,"admin");
        queryWrapper.ge(StrUtil.isNotBlank(params.getStartTime()), User::getCreateTime, params.getStartTime());
        queryWrapper.le(StrUtil.isNotBlank(params.getEndTime()), User::getCreateTime, params.getEndTime());
        queryWrapper.le(StrUtil.isNotBlank(params.getUserLable()), User::getUserLable, params.getUserLable());
        queryWrapper.eq(Objects.nonNull(params.getEnabled()), User::getEnabled, params.getEnabled());
        queryWrapper.orderByDesc(User::getCreateTime);
        Page<User> resultPage = baseMapper.selectPage(page, queryWrapper);
        PageResult<UserRespDTO> userRespDTO = PageResult.of(resultPage, UserRespDTO.class);
//        userRespDTO.getList().forEach(x ->{
//            List<UserRole> userRoles = userRoleService.findByUserId(x.getId());
//            x.setRoles(userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList()));
//        });
        return userRespDTO;
    }

    @Override
    public User getByUsername(Long userId, String username) {
        if (StrUtil.isEmpty(username)) {
            return null;
        }
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
                .eq(User::getUsername, username)
                .ne(ObjectUtil.isNotNull(userId), User::getId, userId);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public User getByNameAndType(Long userId, String username,String userType) {
        if (StrUtil.isEmpty(username)) {
            return null;
        }
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
                .eq(User::getUsername, username)
                .eq(User::getUserType, userType)
                .ne(ObjectUtil.isNotNull(userId) && userId >0, User::getId, userId);
        return baseMapper.selectOne(wrapper);
    }

    public User getByOpenIdUserType(String openId, Integer userType) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
                .eq(User::getEnabled, 0)
                .eq(User::getOpenId, openId)
                .eq(User::getUserType, userType);

        return baseMapper.selectOne(wrapper);
    }

    @Override
    public User getByUserNamePassword(String username, String password, Integer userType) {
        if (StrUtil.isEmpty(username)) {
            return null;
        }
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
                .eq(User::getUsername, username)
                .eq(User::getUserType, userType);
        User user = baseMapper.selectOne(wrapper);
        if(ObjectUtils.isNull(user)){
            throw new BusinessException("您好，用户【"+username+"】不存在～");
        }

        if(user.getEnabled().toString().equals("1")){
            throw new BusinessException("您好，账号【"+username+"】被禁用～");
        }

        if("1".equals(user.getUseLimit())){
            if(user.getDeadlineTime()!=null && !DateUtil.date().before(user.getDeadlineTime())){
                throw new BusinessException("客户服务时间已过期～");
            }
        }

        Long customerId = user.getCustomerId();
        if (customerId != null && customerId != 0){
            Customer customer = customerMapper.selectById(customerId);
            if(customer != null && "1".equals(customer.getIsDeleted().toString())){
                throw new BusinessException("客户【"+customer.getCompanyName()+"】已删除～");
            }
        }
        if (!passwordEncoder.matches(password,user.getPassword())){
            throw new BusinessException("用户名或密码错误～");
        }

        return user;
    }

    @Override
    public Integer changeStatus(Long userId, Integer status) {
        User entity = new User();
        entity.setId(userId);
        entity.setEnabled(status);
        int result = baseMapper.updateById(entity);
        if (status == 1) {
            authService.removeUserSession(userId);
        }
        return result;
    }

    public void logout(){
        Long userId = AuthUtils.getUserId();
        authService.removeUserSession(userId);
    }

    @Override
    public Integer modifyPass(UserPassReqDTO dto) {
        Long userId = AuthUtils.getUserId();
        User user = getById(userId);
        if(!dto.getNewPass().equals(dto.getReNewPass())){
            throw new BizException("新密码与确认密码不一致");
        }
        if (!passwordEncoder.matches(dto.getOldPass(), user.getPassword())) {
            throw new BizException("修改失败，旧密码错误");
        }
        if (passwordEncoder.matches(dto.getNewPass(), user.getPassword())) {
            throw new BizException("新密码不能与旧密码相同");
        }
        if(!pattern.matcher(dto.getNewPass()).matches()){//如果输入符合规则，则返回true，否则返回false
            throw new BizException("密码必须包含6~20位的英文、数字和符号");
        }
        User entity = new User();
        entity.setId(userId);
        entity.setPassword(passwordEncoder.encode(dto.getNewPass()));
        entity.setOriginalPwd(dto.getNewPass());
        return baseMapper.updateById(entity);
    }

    /**
     * 参数校验
     *
     * @param body
     */
    private void checkParams(UserReqDTO body) {
        // 检查用户名是否重复
        if (ObjectUtil.isNotNull(getByNameAndType(body.getId(), body.getUsername(),body.getUserType()))) {
            throw new BizException("账号已存在，请重新输入");
        }

        if(!pattern.matcher(body.getPass()).matches()){//如果输入符合规则，则返回true，否则返回false
            throw new BizException("可输入6~20位，仅支持输入英文、数字和符号");
        }
        // 检查密码和确认密码是否一致
//        String pass = body.getPass();
//        String checkPass = body.getCheckPass();
//        if (ObjectUtil.isNull(body.getId()) && !StrUtil.equals(pass, checkPass)) {
//            throw new BizException("密码和确认密码不一致，请重新输入");
//        }
    }

    @Override
    public Boolean checkName(CheckEmpReqDTO dto){
        String userType = UserTypeEnum.EMPLOYEE.getCode().toString();
        String tipMsg = this.validateUserName(dto.getUsername());
        if(StringUtils.isNotEmpty(tipMsg)){
            throw new BizException(tipMsg);
        }
        if (ObjectUtil.isNotNull(getByNameAndType(dto.getId(), dto.getUsername(),userType ))) {
            throw new BizException("手机号已注册，请重新输入");
        }
        return true;
    }


    /**
     * 添加企业员工
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addEmployee(EmployeeReqDTO dto){
//        String tipMsg = this.validateUserName(dto.getUsername());
//        if(StringUtils.isNotEmpty(tipMsg)){
//            throw new BizException(tipMsg);
//        }
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        String userType = UserTypeEnum.EMPLOYEE.getCode().toString();
        // 检查用户名是否重复
        if (ObjectUtil.isNotNull(getByNameAndType(dto.getId(), dto.getUsername(),userType ))) {
            throw new BizException("手机号已注册，请重新输入");
        }
        User entity = BeanUtil.copyProperties(dto, User.class, "id");
        entity.setPassword(passwordEncoder.encode(dto.getPass()));
        entity.setOriginalPwd(dto.getPass());
        entity.setPhone(dto.getUsername());
        entity.setUserType(userType);
        entity.setUserLable(dto.getUserLable());
        entity.setCustomerId(customerId);
        entity.setCreateBy(AuthUtils.getNickname());
        //如果是添加企业员工
        if(userType.equals(UserTypeEnum.EMPLOYEE.getCode())){
            Customer custBean =  customerMapper.selectById(customerId);
            if(ObjectUtil.isEmpty(custBean)){
                throw new BizException("企业信息为空");
            }
            entity.setEmpCheckState(custBean.getCheckMode());//企业员工审核状态（0-未审核，1-审核通过）
        }
        Integer result = baseMapper.insert(entity);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateEmployee(EmployeeReqDTO dto) {
//        String tipMsg = this.validateUserName(dto.getUsername());
//        if(StringUtils.isNotEmpty(tipMsg)){
//            throw new BizException(tipMsg);
//        }
        String userType = UserTypeEnum.EMPLOYEE.getCode().toString();
        // 检查用户名是否重复
        if (ObjectUtil.isNotNull(getByNameAndType(dto.getId(), dto.getUsername(),userType ))) {
            throw new BizException("手机号已注册，请重新输入");
        }
        User tmpUser = getById(dto.getId());
        if(ObjectUtils.isNull(tmpUser)){
            throw new BusinessException("您好，用户不存在～");
        }
        User user = BeanUtil.copyProperties(dto, User.class);
        user.setPhone(dto.getUsername());//账号就是手机号
        user.setOriginalPwd(dto.getPass());
        user.setPassword(passwordEncoder.encode(dto.getPass()));
        int result = baseMapper.updateById(user);
        if (dto.getEnabled() == 1) {
            authService.removeUserSession(dto.getId());
        }
        return result;
    }

    @Override
    public UserRespDTO getEmpUserById(Long userId) {
        User user = getById(userId);
        UserRespDTO userRespDTO = BeanUtil.copyProperties(user, UserRespDTO.class);
        return userRespDTO;
    }

    @Override
    public PageResult<EmployeeRespDTO> pageEmpList(EmpQueryReqDTO params){
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        Page<User> page = params.buildPage();
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.and(
                StrUtil.isNotBlank(params.getQ()),
                wrapper -> wrapper.like(User::getUsername, params.getQ())
                        .or()
                        .like(User::getNickName, params.getQ())
        );
        queryWrapper.eq(User::getUserType,UserTypeEnum.EMPLOYEE.getCode());
        queryWrapper.eq(User::getCustomerId, customerId);
        queryWrapper.eq(StrUtil.isNotBlank(params.getUserLable()), User::getUserLable, params.getUserLable());
        queryWrapper.eq(params.getEnabled()!=null, User::getEnabled, params.getEnabled());
        if("desc".equals(params.getOrderType())){
            queryWrapper.orderByDesc(User::getCreateTime);
        }else{
            queryWrapper.orderByAsc(User::getCreateTime);
        }

        //此IF逻辑需要处理-过滤掉加入过
        if(params.getCourseId() != null && params.getCourseId() >0){
            LambdaQueryWrapper<CourseUser> queryCourseUserWrapper = Wrappers.lambdaQuery();
            queryCourseUserWrapper.eq(CourseUser::getCourseId,params.getCourseId());
            queryCourseUserWrapper.eq(CourseUser::getCustomerId,customerId);
            List<CourseUser> courseUserList = courseUserMapper.selectList(queryCourseUserWrapper);
            if(ObjectUtil.isNotEmpty(courseUserList)){
                List<Long> courseUserIds = courseUserList.stream()               // 创建流
                                        .map(CourseUser::getUserId) // 取出每个对象的 userId
                                        .filter(Objects::nonNull) // 可选：去掉 null 值
                                        .collect(Collectors.toList());
                if (ObjectUtil.isNotEmpty(courseUserIds)) {
                    queryWrapper.notIn(User::getId, courseUserIds);
                }
            }
        }

        Page<User> resultPage = baseMapper.selectPage(page, queryWrapper);
        List<User> records = resultPage.getRecords();
        if (CollUtil.isNotEmpty(records)){
            List<String> collect = records.stream().map(User::getCreateBy).collect(Collectors.toList());
            LambdaQueryWrapper<User> q = Wrappers.lambdaQuery();
            q.in(User::getUsername, collect);
            List<User> userList = baseMapper.selectList(q);
            if (CollUtil.isNotEmpty(userList)){
                for (User record : records) {
                    Optional<User> userOptional = userList.stream()
                            .filter(user -> user.getUsername().equals(record.getCreateBy()))
                            .findFirst();
                    userOptional.ifPresent(user -> record.setCreateBy(user.getNickName()));
                }
            }
        }
        return PageResult.of(resultPage, EmployeeRespDTO.class);
    }

    /**
     * 获取企业员工待审核的用户列表
     * @param params
     * @return
     */
    @Override
    public PageResult<EmployeeRespDTO> checkEmployeeList(PageParam params){
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        Page<User> page = params.buildPage();
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(User::getUserType,UserTypeEnum.EMPLOYEE.getCode());
        queryWrapper.eq(User::getCustomerId, customerId);
        queryWrapper.eq(User::getEmpCheckState,0);//企业员工审核状态（0-未审核，1-审核通过）
        Page<User> resultPage = baseMapper.selectPage(page, queryWrapper);
        return PageResult.of(resultPage, EmployeeRespDTO.class);
    }

    /**
     * 批量审核员工状态
     * @param dto
     * @return
     */
    @Override
    public boolean batchEmpCheck(BatchIdsDTO dto){
        if(ObjectUtil.isEmpty(dto.getIds())){
            throw new BizException("请选择待审核注册员工");
        }
        if(dto.getStatus() !=null && CheckStatusEnum.APPROVED.getCode() != dto.getStatus()
                && CheckStatusEnum.WAIT_CHECK.getCode()!= dto.getStatus()){
            throw new BizException("参数status值不正确～");
        }
        for (Long id : dto.getIds()) {
            User entity = baseMapper.selectById(id);
            if(ObjectUtil.isEmpty(entity)){
                throw new BizException("用户记录为空～");
            }
            if(CheckStatusEnum.APPROVED.getCode() == dto.getStatus()){ //如果是审核通过
                entity.setEmpCheckState(CheckStatusEnum.APPROVED.getCode());//企业员工审核状态（0-未审核，1-审核通过）
                entity.setUpdateTime(new Date());
                baseMapper.updateById(entity);
            }else{
                baseMapper.deleteById(entity);
            }
        }
        return true;

    }

    /**
     *  查询获取企业员工（过滤掉已加入课程的员工）
     * @param params
     * @return
     */
    @Override
    public PageResult<EmployeeRespDTO> findNotCourseUserList(EmpQueryReqDTO params){
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        if(params.getCourseId() == null || params.getCourseId() ==0){
            throw new BizException("课程ID[courseId]参数必须");
        }
        Page<EmployeeRespDTO> resultPage = baseMapper.selectNotCourseUserList(params.buildPage(), customerId,params.getCourseId(),params.getUserLable(),params.getQ());
        return PageResult.of(resultPage, EmployeeRespDTO.class);
    }

    @Override
    @Transactional
    public List<EmpImportDTO> checkExcelData(List<EmpImportDTO> importList) {
        return this.checkImportData(importList);
    }

    @Override
    @Transactional
    public boolean saveExcelData(List<EmpImportDTO> importList){
        List<EmpImportDTO> list= this.checkImportData(importList);
        String userType = UserTypeEnum.EMPLOYEE.getCode().toString();
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();

        int importCount = importList.size();
        long passedCount = list.stream().filter(dto -> "检验通过".equals(dto.getMessage())).count();
        if(importCount != passedCount){
            throw new BizException("导入文档有不正确数据，请先进行验证查看异常信息～");
        }
        log.info("importCount == passedCount");
        //获取企业信息的审核模式类型
//        Customer custBean =  customerMapper.selectById(customerId);
//        if(ObjectUtil.isEmpty(custBean)){
//            throw new BizException("企业信息为空");
//        }
//        Integer checkMode = custBean.getCheckMode();
        for(EmpImportDTO paramBean : importList){
            User entity = new User();
            entity.setUsername(paramBean.getUsername());
            entity.setNickName(paramBean.getNickName());
            entity.setUserLable(paramBean.getUserLable());
            entity.setPassword(passwordEncoder.encode(paramBean.getPass()));
            entity.setOriginalPwd(paramBean.getPass());
            entity.setPhone(paramBean.getUsername());
            entity.setUserType(userType);
            entity.setCustomerId(customerId);
            //如果是添加企业员工审核状态
            entity.setEmpCheckState(1);//企业员工审核状态（0-未审核，1-审核通过）----管理员导入或手动选人加入都是不用审核的
            baseMapper.insert(entity);
        }
        return true;
    }

    private List<EmpImportDTO> checkImportData(List<EmpImportDTO> importList){
        if(CollectionUtil.isEmpty(importList)){
            throw new BusinessException("没有要导入的单位人员数据");
        }
        List<EmpImportDTO> dataList = new ArrayList<EmpImportDTO>();

        Map<String, Integer> firstRowMap = new HashMap<>(importList.size());//文档内重复校验辅助

        for(int i=0;i<importList.size();i++){
            EmpImportDTO importBean = importList.get(i);
            String username = importBean.getUsername();
            StringBuffer sb = new StringBuffer();
            if(!ToolUtil.isValidName(importBean.getNickName())){
                sb.append("【姓名请输入1-20位中文、英文或数字】；");
            }
            if(!ToolUtil.isValidPassword(importBean.getPass())){
                sb.append("【密码请输入6-20位英文、数字或符号】；");
            }
            if(!ToolUtil.isValidAccount(username)){
                sb.append("【账号请输入6-20位英文或数字】；");
            }
            if(StringUtils.isNotBlank(username)){
                Integer firstRow = firstRowMap.put(username, i + 1); // 返回旧值（首次行号）
                if(firstRow != null){
                    sb.append("【该账号在文档中有重复数据】；");
                }
                // 检查用户名是否重复
                String userType = UserTypeEnum.EMPLOYEE.getCode().toString();
                if (ObjectUtil.isNotNull(getByNameAndType(null, username,userType ))) {
                    sb.append( "【该账号在系统中已存在】；");
                }
            }
            importBean.setOrderNo(i+1);
            if(StringUtils.isNotEmpty(sb)){
                importBean.setMessage(sb.toString());
            }else{
                importBean.setMessage("检验通过");
            }
            dataList.add(importBean);
        }
        return  dataList;
    }

    /**
     * 校验入口
     * @param name 待校验姓名
     * @return 校验通过返回 null；否则返回错误提示
     */
    public static String validateUserName(String name) {
        if (name == null || name.isEmpty()) {
            return ERROR_MSG;   // 必填
        }
        if (!PATTERN_USERNAME.matcher(name).matches()) {
            return ERROR_MSG;   // 格式或长度不符
        }
        return null;            // 通过
    }

    /**
     * 更新用户状态
     * @return
     */
    @Override
    public Integer updateUserEnable(){
        return baseMapper.updateUserEnable();
    }

    @Override
    public Integer clearUserWxOpenId(Long userId){
        return baseMapper.clearUserWxOpenId(userId);
    }

    @Override
    public Integer stopUserEnabled(Long enabled){
        return baseMapper.stopUserEnabled(enabled);
    }

}
